import Layout from "../Shared/Layout";
import { Tree, Descriptions, message, Popconfirm, Input } from "antd";
import MyButton from "../../Components/MyButton";
import React, { useState, useEffect } from "react";
import { useDispatch } from "react-redux";
import { request, requestDispatch } from "../../Api/api";
import AddDepartment from "../../Components/Operation/Department/AddDepartment";
const Department = () => {
  const [departmentTrees, setDepartmentTrees] = useState([]);
  const [currDepartment, setCurrDepartment] = useState({});
  const [addingDep, setAddingDep] = useState({
    name: "",
    explain: "",
    parentId: undefined,
  });
  const [updatingDep, setUpdatingDep] = useState({});
  const [isUpdating, setIsUpdating] = useState(false);
  const [addShow, setAddShow] = useState(false);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const dispatch = useDispatch();
  const items = [
    {
      key: "1",
      label: "编号",
      children: <p>{currDepartment.id}</p>,
    },
    {
      key: "2",
      label: "名称",
      children: isUpdating ? (
        <div>
          <Input
            value={updatingDep.name}
            onChange={(e) =>
              setUpdatingDep({ ...updatingDep, name: e.target.value })
            }
          ></Input>
        </div>
      ) : (
        <p>{currDepartment.name}</p>
      ),
    },
    {
      key: "3",
      label: "创建时间",
      children: (
        <p>{new Date(currDepartment.createTime).toLocaleDateString()}</p>
      ),
    },
    {
      key: "4",
      label: "描述",
      children: isUpdating ? (
        <div>
          <Input.TextArea
            rows={4}
            value={updatingDep.explain}
            onChange={(e) =>
              setUpdatingDep({ ...updatingDep, explain: e.target.value })
            }
          ></Input.TextArea>
        </div>
      ) : (
        <p>{currDepartment.explain}</p>
      ),
    },
  ];

  // 初始化数据
  useEffect(() => {
    async function fetchData() {
      // You can await here
      const response = await requestDispatch(
        dispatch,
        "/department/tree",
        {},
        "GET"
      );
      if (response.code >= 0) {
        setDepartmentTrees(response.data);
        setCurrDepartment(response.data[0]);
        setExpandedKeys(getAllKeys(response.data));
      }
    }
    fetchData();
    // 获取所有节点的 key
    const getAllKeys = (data) => {
      let keys = [];
      data.forEach((item) => {
        keys.push(item.id);
        if (item.childrenDeps) {
          keys = keys.concat(getAllKeys(item.childrenDeps));
        }
      });
      return keys;
    };
  }, [dispatch]);

  // 选择部门
  const selectedChange = (keys, e) => {
    if (e.selected) {
      setCurrDepartment(e.node);
    }
  };

  // 执行实际操作 begin
  // 新增部门
  const addDep = async (dep) => {
    let res = await request("/department/add", { ...dep }, "post");
    if (res.code >= 0) {
      message.success(res.message);
      setDepartmentTrees(
        departmentTreesAdd(departmentTrees, dep.parentId, res.data)
      );
    } else {
      message.error(res.message);
    }
  };
  // 删除部门
  const deleteDep = async (id) => {
    let res = await requestDispatch(
      dispatch,
      "/department/delete",
      { id: id },
      "post"
    );
    if (res.code >= 0) {
      message.success(res.message);
      setDepartmentTrees(departmentTreesRemove(departmentTrees, id));
      setCurrDepartment(departmentTrees[0]);
    } else {
      message.error(res.message);
    }
  };
  // 更新部门
  const updateDep = async (dep) => {
    let res = await requestDispatch(
      dispatch,
      "/department/update",
      { ...dep },
      "post"
    );
    if (res.code >= 0) {
      setIsUpdating(false);
      message.success(res.message);
      setDepartmentTrees(
        departmentTreesUpdate(departmentTrees, {
          ...dep,
          createTime: new Date(dep.createTime).toLocaleDateString(),
        })
      );
      setCurrDepartment(dep);
    } else {
      message.error(res.message);
    }
  };
  // 执行实际操作 end

  // 更新本地数据 begin
  // 删除部门
  const departmentTreesRemove = (trees, id) => {
    return trees.reduce((acc, item) => {
      // 递归处理子节点
      const updatedChildren = item.childrenDeps
        ? departmentTreesRemove(item.childrenDeps, id)
        : [];

      // 如果当前节点的 ID 不等于要移除的 ID，则保留
      if (item.id !== id) {
        acc.push({
          ...item,
          childrenDeps: updatedChildren, // 更新子节点
        });
      } else {
        // 如果当前节点被移除，可以选择不推入，这样它就不会出现在结果中
      }

      return acc;
    }, []);
  };
  // 新增部门
  const departmentTreesAdd = (trees, parentId, dep) => {
    return trees.reduce((acc, item) => {
      // 递归处理子节点
      const updatedChildren = item.childrenDeps
        ? departmentTreesAdd(item.childrenDeps, parentId, dep)
        : [];
      // 如果当前节点的 ID 等于要新增的父节点 ID，则新增一个子节点
      if (item.id === parentId) {
        acc.push({
          ...item,
          childrenDeps: [
            { ...dep, selectable: true },
            ...updatedChildren, // 更新子节点
          ],
        });
      } else {
        // 如果当前节点的 ID 不等于要新增的父节点 ID，则保留
        acc.push({
          ...item,
          childrenDeps: updatedChildren, // 更新子节点
        });
      }
      return acc;
    }, []);
  };

  // 修改部门
  const departmentTreesUpdate = (trees, dep) => {
    return trees.reduce((acc, item) => {
      // 递归处理子节点
      const updatedChildren = item.childrenDeps
        ? departmentTreesRemove(item.childrenDeps, dep)
        : [];

      // 如果当前节点的 ID 不等于要更新的 ID，则保留
      if (item.id !== dep.id) {
        acc.push({
          ...item,
          childrenDeps: updatedChildren, // 更新子节点
        });
      } else {
        // 如果当前节点被移除，可以选择不推入，这样它就不会出现在结果中
        acc.push({
          ...dep,
          childrenDeps: [
            ...updatedChildren, // 更新子节点
          ],
        });
      }

      return acc;
    }, []);
  };
  // 更新本地数据 end

  // 显示新增部门弹窗
  const showAddModal = () => {
    setAddingDep({
      name: "",
      explain: "",
      parentId: currDepartment.id,
    });
    setAddShow(true);
  };
  // 切换编辑模式
  const toggleUpdate = async () => {
    if (isUpdating) {
      updateDep(updatingDep);
    } else {
      setUpdatingDep({
        id: currDepartment.id,
        name: currDepartment.name,
        explain: currDepartment.explain,
      });
      setIsUpdating(true);
    }
  };
  return (
    <Layout>
      <AddDepartment
        dep={addingDep}
        open={addShow}
        onOk={(dep) => {
          addDep(dep);
          setAddShow(false);
        }}
        onCancel={() => setAddShow(false)}
      ></AddDepartment>
      <div className="container">
        <div className="container-left">
          <Tree
            treeData={departmentTrees}
            defaultExpandAll={true}
            expandedKeys={expandedKeys}
            onExpand={(keys) => setExpandedKeys(keys)}
            fieldNames={{
              title: "name",
              key: "id",
              children: "childrenDeps",
            }}
            blockNode
            onSelect={selectedChange}
          />
        </div>
        <div className="container-right">
          <Descriptions
            layout="vertical"
            bordered
            items={items}
            title="部门信息"
            extra={
              isUpdating ? (
                <div className="extra">
                  <div
                    className="extra-btn"
                    onClick={() => setIsUpdating(false)}
                  >
                    <MyButton>{"取消"}</MyButton>
                  </div>
                  <div className="extra-btn" onClick={toggleUpdate}>
                    <MyButton type={"primary"}>{"保存"}</MyButton>
                  </div>
                </div>
              ) : (
                <div className="extra">
                  <Popconfirm
                    title="删除部门"
                    description="您确定要删除该部门吗?"
                    onConfirm={() => deleteDep(currDepartment.id)}
                    okText="确认"
                    cancelText="取消"
                  >
                    <div className="extra-btn">
                      <MyButton type="danger">删除</MyButton>
                    </div>
                  </Popconfirm>
                  <div className="extra-btn" onClick={showAddModal}>
                    <MyButton type="success">新增子级</MyButton>
                  </div>
                  <div className="extra-btn" onClick={toggleUpdate}>
                    <MyButton type={isUpdating ? "primary" : "warning"}>
                      {isUpdating ? "保存" : "编辑"}
                    </MyButton>
                  </div>
                </div>
              )
            }
          />
        </div>
      </div>
    </Layout>
  );
};

export default Department;
